-- 初始化 company_finance_db 数据库 - 客户管理
-- 运行: psql -U postgres -f init-db.sql

-- 创建数据库（如果不存在）
SELECT 'CREATE DATABASE company_finance_db'
WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'company_finance_db')\gexec

-- 连接到新数据库
\c company_finance_db

-- 删除现有表（如果存在）
DROP TABLE IF EXISTS contacts;
DROP TABLE IF EXISTS customers;

-- 创建customers表
CREATE TABLE customers (
  id SERIAL PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  email VARCHAR(100) UNIQUE NOT NULL,
  phone VARCHAR(20),
  address TEXT,
  company VARCHAR(100),
  tax_id VARCHAR(50),
  status VARCHAR(20) DEFAULT 'active',
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 创建contacts表
CREATE TABLE contacts (
  id SERIAL PRIMARY KEY,
  customer_id INTEGER REFERENCES customers(id) ON DELETE CASCADE,
  name VARCHAR(100) NOT NULL,
  position VARCHAR(100),
  email VARCHAR(100),
  phone VARCHAR(20),
  is_primary BOOLEAN DEFAULT false,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- 创建索引
CREATE INDEX idx_customers_email ON customers(email);
CREATE INDEX idx_customers_status ON customers(status);
CREATE INDEX idx_contacts_customer_id ON contacts(customer_id);

-- 插入示例客户数据
INSERT INTO customers (name, email, phone, address, company, tax_id, status) VALUES
('张三', 'zhangsan@example.com', '13800138000', '北京市朝阳区', 'ABC科技有限公司', '91110108MA01ABCDEF', 'active'),
('李四', 'lisi@example.com', '13900139000', '上海市浦东新区', 'XYZ有限公司', '91310115MA01XYZ123', 'active'),
('王五', 'wangwu@example.com', '13700137000', '广州市天河区', 'DEF集团', '91440101MA01DEF456', 'inactive'),
('赵六', 'zhaoliu@example.com', '13600136000', '深圳市南山区', 'GHI有限公司', '91440300MA01GHI789', 'active'),
('钱七', 'qianqi@example.com', '13500135000', '杭州市西湖区', 'JKL集团', '91330100MA01JKL012', 'active');

-- 插入示例联系人数据
INSERT INTO contacts (customer_id, name, position, email, phone, is_primary) VALUES
(1, '张三', '总经理', 'zhangsan@example.com', '13800138000', true),
(1, '李助理', '总经理助理', 'assistant@abc.com', '13800138001', false),
(2, '李四', '技术总监', 'lisi@example.com', '13900139000', true),
(2, '王经理', '销售经理', 'sales@xyz.com', '13900139001', false),
(3, '王五', '财务总监', 'wangwu@example.com', '13700137000', true),
(4, '赵六', '运营总监', 'zhaoliu@example.com', '13600136000', true),
(5, '钱七', '市场总监', 'qianqi@example.com', '13500135000', true);

-- 显示表结构
\d customers
\d contacts

-- 显示数据统计
SELECT 'Customers:' as table_name, COUNT(*) as record_count FROM customers
UNION ALL
SELECT 'Contacts:', COUNT(*) FROM contacts;

-- 显示示例数据
SELECT '=== Customers Table ===' as info;
SELECT * FROM customers ORDER BY id;

SELECT '=== Contacts Table ===' as info;
SELECT * FROM contacts ORDER BY customer_id, is_primary DESC;