-- 무료용 대상자 관리(스크린샷형) 데이터 반영
-- 실행 예:
--   mysql --default-character-set=utf8mb4 -h 116.122.157.166 -u jongryangje -p jongryangje_dev < writable/database/free_recipient_seed_from_screenshot.sql

SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci;
SET CHARACTER_SET_CLIENT = utf8mb4;

-- 대상 지자체: 대구 북구(lg_code=110209) 우선, 없으면 최소 활성 lg_idx
SET @lg_idx := COALESCE(
  (SELECT lg_idx FROM local_government WHERE lg_code = '110209' AND lg_state = 1 LIMIT 1),
  (SELECT lg_idx FROM local_government WHERE lg_state = 1 ORDER BY lg_idx ASC LIMIT 1)
);

-- 1) 동사무소(기관) 대상: 해당 지자체 동코드(D) 전체를 기본 등록
INSERT INTO free_recipient
(
  fr_lg_idx, fr_type_code, fr_name, fr_phone, fr_addr,
  fr_dong_code, fr_note, fr_end_date, fr_state, fr_regdate
)
SELECT
  @lg_idx,
  'office',
  '읍.면.동 사무소',
  '',
  '',
  d.cd_code,
  d.cd_name,
  '9999-12-31',
  1,
  NOW()
FROM code_detail d
INNER JOIN code_kind k ON k.ck_idx = d.cd_ck_idx
WHERE k.ck_code = 'D'
  AND d.cd_state = 1
  AND (d.cd_lg_idx IS NULL OR d.cd_lg_idx = @lg_idx)
  AND d.cd_code <> ''
  AND NOT EXISTS (
    SELECT 1
    FROM free_recipient f
    WHERE f.fr_lg_idx = @lg_idx
      AND f.fr_type_code = 'office'
      AND f.fr_dong_code = d.cd_code
  );

-- 2) 무료 대상자(기관/부서) 샘플: 스크린샷 하단 형태 반영
INSERT INTO free_recipient
(
  fr_lg_idx, fr_type_code, fr_name, fr_phone, fr_addr,
  fr_dong_code, fr_note, fr_end_date, fr_state, fr_regdate
)
SELECT
  @lg_idx,
  'target',
  t.fr_name,
  '',
  '',
  '',
  '스크린샷형 기본 데이터',
  '9999-12-31',
  1,
  NOW()
FROM (
  SELECT '한강관리과' AS fr_name
  UNION ALL SELECT '항무과'
  UNION ALL SELECT '도시시설기획과'
  UNION ALL SELECT '국민복지과'
  UNION ALL SELECT '자원순환과'
  UNION ALL SELECT '교통과'
  UNION ALL SELECT '대구시설과'
  UNION ALL SELECT '공지인격과'
  UNION ALL SELECT '재무과'
) t
WHERE NOT EXISTS (
  SELECT 1
  FROM free_recipient f
  WHERE f.fr_lg_idx = @lg_idx
    AND f.fr_type_code = 'target'
    AND f.fr_name = t.fr_name
);
